﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace DLL
{
   public class Sys_last_code_id
    {
        public string Table_name { get; set; }
        public int Code_id { get; set; }
        public int Length { get; set; }
        public string Prefix { get; set; }
        public string Suffix { get; set; }
    }
   public class Sys_last_code_id_DAL
   {
       public Sys_last_code_id SelectbyKey(string tenbang)
       {
           string selectcmd = "select * from Sys_last_code_id where Table_name = '" + tenbang + "'";
           SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["QLCH"].ConnectionString);
           SqlCommand cmd = new SqlCommand(selectcmd, conn);
           conn.Open();
           //Thuc thi lay ket qua
           Sys_last_code_id entity = null;
           //reader la obj de tro toi kq
           SqlDataReader reader = cmd.ExecuteReader();
           if (reader.Read())
           {
               entity = new Sys_last_code_id();
               entity.Prefix = reader.GetString(reader.GetOrdinal("Prefix"));
               entity.Length = reader.GetInt32(reader.GetOrdinal("Length"));//kieu so nguyen
               //lay stt cua cot do trong cau lenh select 
               entity.Code_id = reader.GetInt32(reader.GetOrdinal("Code_id"));
           }

           conn.Close();
           return entity;
       }
       //sinh ma xong phai cap nhat tang len
       public void UpdateKey(string tenbang)
       {
           string cmdstring = "update Sys_last_code_id set Code_id=Code_id+1 where Table_name='" + tenbang + "'";
           SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["QLCH"].ConnectionString);
           SqlCommand cmd = new SqlCommand(cmdstring, conn);
           conn.Open();
           cmd.ExecuteNonQuery();
           conn.Close();
       }
   }
   public class CommonFunc
   {
       public static string GetPrimaryKey(string tablename)
       {
           Sys_last_code_id_DAL objDao = new Sys_last_code_id_DAL();
           Sys_last_code_id entity = objDao.SelectbyKey(tablename);
           if (entity != null)
           {
               int id = entity.Code_id;
               int kl = entity.Length;
               int pl = entity.Prefix.Length;
               //Padleft them 0 vao trai
               return entity.Prefix + id.ToString().PadLeft(kl - pl, '0');
           }
           else
               return "";
       }
       //dung xong khoa phai cap nhat lai (vd tang 1 neu dung theo tt)
       public static void UpdatePrimaryKey(string table)
       {
           Sys_last_code_id_DAL objDao = new Sys_last_code_id_DAL();
           objDao.UpdateKey(table);
       }
   }
}
